import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebWidget extends StatefulWidget {
  AppBar? appBar;
  String? URI;
  WebViewController? viewController;

  WebWidget({this.appBar, this.URI});

  @override
  _WebWidgetState createState() => _WebWidgetState();

  exceJavascript(String excute) async {
    if (null != viewController) {
      viewController
          ?.evaluateJavascript(
              'callbackDemo("Demo回调Demo回调Demo回调Demo回调Demo回调");')
          .then((result) {
        //print('您可以在此处处理JS结果1');
        return '您可以在此处处理JS结果1';
      });
    }
  }
}

class _WebWidgetState extends State<WebWidget> {
  late WebView webViewx;
  late WebViewController _vc;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //使用插件 FaiWebViewWidget
    webViewx = WebView(
      initialUrl: widget.URI,

      ///初始化url
      javascriptMode: JavascriptMode.unrestricted,

      ///JS执行模式),
      onWebViewCreated: (WebViewController webViewController) {
        ///在WebView创建完成后调用，只会被调用一次
        //setState(() {
        _vc = webViewController;
        widget.viewController = webViewController;
        //});
        //widget._viewController = webViewController;
      },
      onPageFinished: (String url) {
        ///页面加载完成回调
//        setState(() {
//          _loading = false;
//        });
        // TODO 去掉遮罩（遮罩层未实现）
      },
      javascriptChannels: <JavascriptChannel>[
        ///JS和Flutter通信的Channel；
//        _alertJavascriptChannel(context),
      ].toSet(),
      navigationDelegate: (NavigationRequest request) {
        //路由委托（可以通过在此处拦截url实现JS调用Flutter部分）；
        ///通过拦截url来实现js与flutter交互
        if (request.url.startsWith('js://webview')) {
//          Fluttertoast.showToast(msg:'JS调用了Flutter By navigationDelegate');
          print('blocking navigation to $request}');
          return NavigationDecision.prevent;

          ///阻止路由替换，不能跳转，因为这是js交互给我们发送的消息
        }

        return NavigationDecision.navigate;

        ///允许路由替换
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.appBar != null ? widget.appBar : null,
      body: buildRefreshHexWidget(),
    );
  }

  Widget buildRefreshHexWidget() {
    return RefreshIndicator(
      //下拉刷新触发方法
      onRefresh: () async {
        print('refresh');
      },
      //设置webViewWidget
      child: webViewx != null ? webViewx : Text('未加载成功'),
    );
  }
}
